var fs = require('fs');
K = {};

K.apply = function(o, c, defaults) {
    // no "this" reference for friendly out of scope calls
    if (defaults) {
        K.apply(o, defaults);
    }
    if (o && c && typeof c === 'object') {
        for (var p in c) {
            o[p] = c[p];
        }
    }
    return o;
};



function KSystem(cfg) {
    this.cfg = cfg || {path: '', request: null};
    K.apply(this, cfg);
    this.readylistener = function() {
    };
}
;
K.apply(KSystem.prototype, {
    onReady: function(listener) {
        this.readylistener = listener;
    },
    execute: function() {
        var parts = this.path.split('/');
		var methodname = parts[parts.length - 1];
		var s = methodname.length;
		var filename = './mod/' + (this.path.substr(0, (this.path.length - (s + 1)))) + '.js';
		fs.exists('./kirchrath/'+filename, function(e) {
			if (e) {
				var module = require(filename);
				var method = module[methodname];
				method(this.request, this.readylistener);
			} else {
				this.readylistener({
					success: false,
					message: 'Module file not found: ' + filename
				});
			}
		}.bind(this));
    }
});
module.exports = KSystem;